import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Alert,
  TouchableWithoutFeedback,
  Keyboard,
} from 'react-native';
import theme from '../utils/theme';
import useHideTabBar from '../utils/useHideTabBar';
import API from '../Network/Api';
import Toast from 'react-native-toast-message';
import {showToast} from '../utils/toastUtils';
import {getData} from '../utils/storageUtils';
import { CustomText } from "../customview/CustomText";
import { normalize } from "../utils/commonUtils";

const AddressPage = ({navigation}) => {
  const [address, setAddress] = useState('');
  const [phone, setPhone] = useState('');
  useHideTabBar(navigation);

  useEffect(() => {
    const loadUserInfo = async () => {
      try {
        const loginInfo = await getData('userInfoKey');
        if (loginInfo) {
          if (loginInfo.address) {
            setAddress(loginInfo.address);
          }
          if (loginInfo.phone) {
            setPhone(loginInfo.phone);
          }
        }
      } catch (error) {
        console.error('读取本地用户信息失败:', error);
      }
    };

    loadUserInfo();
  }, []);

  const handleAuthentication = () => {
    if (address.length <= 10) {
      showToast({text2: '请填写地址详细！'});
      return;
    }
    API.modifyUserAddressReq(address, phone)
      .then(response => {
        if (response.resultCode === '1') {
          Alert.alert('提示', '地址提交成功！');
        } else {
          showToast({
            text2: response.showMsg,
          });
        }
      })
      .catch(error => {
        showToast({
          text2: '实名认证失败，请联系管理员！',
        });
      });
  };

  const dismissKeyboard = () => {
    Keyboard.dismiss();
  };

  return (
    <TouchableWithoutFeedback onPress={dismissKeyboard}>
      <View style={styles.container}>
        <View style={styles.inputContainer}>
          <View style={{flexDirection: 'row', alignItems: 'center'}}>
            <CustomText style={styles.label}>地址  </CustomText>
            <CustomText style={styles.addressTip}>
              ( 例：江苏省扬州市广陵区某某小区2-1001 )
            </CustomText>
          </View>
          <TextInput
            allowFontScaling={false}
            style={styles.input}
            placeholder="请输入收货地址"
            value={address}
            multiline={true} // 设置为多行输入
            numberOfLines={1} // 初始显示的行数
            textAlignVertical="top" // 文本垂直顶部对齐
            onChangeText={(text) => setAddress(text)}
          />
        </View>
        <CustomText style={styles.tip}>
          请填写真实有效的地址信息，如果信息填写错误导致收货失败，后果自负。
        </CustomText>
        <TouchableOpacity style={styles.authenticationButton} onPress={handleAuthentication}>
          <CustomText style={styles.buttonText}>确认提交</CustomText>
        </TouchableOpacity>
        <Toast />
      </View>
    </TouchableWithoutFeedback>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    padding: 20,
  },
  inputContainer: {
    marginBottom: 20,
  },
  label: {
    fontSize: normalize(16),
    fontWeight: '500',
  },
  addressTip: {
    fontSize: normalize(12),
    color: '#999',
  },
  input: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    fontSize: normalize(16),
    marginTop: 8,
  },
  tip: {
    fontSize: normalize(14),
    color: '#999',
    marginBottom: 20,
  },
  authenticationButton: {
    backgroundColor: theme.colors.primary,
    borderRadius: 8,
    alignItems: 'center',
    padding: 15
  },
  buttonText: {
    color: '#fff',
    fontSize: normalize(18),
    fontWeight: 'bold',
  },
});

export default AddressPage;
